<?php

namespace App\Http\Middleware;

use App\Models\Admin\Permission;
use Closure;
use View;
use Zizaco\Entrust\EntrustFacade as Entrust;
use Route,URL,Auth;

class AuthenticateAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if(Auth::guard('admin')->user()->is_super){
            return $next($request);
        }

        $previousUrl = URL::previous();
        if(!Auth::guard('admin')->user()->can(Route::currentRouteName())) {
            if($request->ajax() && ($request->getMethod() != 'GET')) {
                return response()->json([
                    'status' => -1,
                    'code' => 403,
                    'msg' => '您没有权限执行此操作'
                ]);
            } else {

                dd("您没有权限执行此操作");
                return view('admin.errors.403')->with(['previousUrl' => $previousUrl]);
            }
        } else {
            // 生成左侧导航
            $father = Permission::where('fid', 0)->where('is_menu', 1)->orderBy('sort')->orderBy('id')->get()->toArray();
            if ($father) {
                foreach ($father as $item) {
                    if ($item['sub_permission']) {
                        foreach ($item['sub_permission'] as $key => $sub) {
                            if ($sub['is_menu']) {
                                $item['sub'][] = $sub;
                            }
                        }
                        unset($item['sub_permission']);
                    }
                    $menus[] = $item;
                }
            }
//            dd($menus);
            View::share('menus', $menus);
        }
        $response  = $next($request);
        return $response;
//        return $next($request);
    }
}
